package dao;

import pojo.Place;
import utils.JDBCUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class PlaceDAO {

    private static final String TABLE_NAME = "tb_place";

    // 获取所有景点信息
    public static List<Place> getAllPlaces() throws SQLException {
        List<Place> places = new ArrayList<>();
        String sql = "SELECT * FROM " + TABLE_NAME;
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql);
        while (resultSet.next()) {
            Place place = createPlaceFromResultSet(resultSet);
            places.add(place);
        }
        return places;
    }

    // 根据ID获取景点信息
    public static Place getPlaceById(int id) throws SQLException {
        String sql = "SELECT * FROM " + TABLE_NAME + " WHERE place_id = ?";
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql, id);
        if (resultSet.next()) {
            return createPlaceFromResultSet(resultSet);
        }
        return null;
    }

    // 创建Place对象从ResultSet
    private static Place createPlaceFromResultSet(ResultSet resultSet) throws SQLException {
        int placeId = resultSet.getInt("place_id");
        String name = resultSet.getString("name");
        String description = resultSet.getString("description");
        String location = resultSet.getString("location");
        String tickets = resultSet.getString("tickets");
        String openHours = resultSet.getString("open_hours");
        String imageUrl = resultSet.getString("image_url");

        Place place = new Place();
        place.setPlaceId(placeId);
        place.setName(name);
        place.setDescription(description);
        place.setLocation(location);
        place.setTickets(tickets);
        place.setOpenHours(openHours);
        place.setImageUrl(imageUrl);
        return place;
    }

    // 插入景点信息
    public static void insertPlace(Place place) throws SQLException {
        String sql = "INSERT INTO " + TABLE_NAME + " (name, description, location, tickets, open_hours, image_url) VALUES (?, ?, ?, ?, ?, ?)";
        JDBCUtils.execute(sql, place.getName(), place.getDescription(), place.getLocation(),
                place.getTickets(), place.getOpenHours(), place.getImageUrl());
    }

    // 更新景点信息
    public static void updatePlace(Place place) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME + " SET name = ?, description = ?, location = ?, tickets = ?, open_hours = ?, image_url = ? WHERE place_id = ?";
        JDBCUtils.execute(sql, place.getName(), place.getDescription(), place.getLocation(),
                place.getTickets(), place.getOpenHours(), place.getImageUrl(), place.getPlaceId());
    }

    // 删除景点信息
    public static void deletePlace(int id) throws SQLException {
        String sql = "DELETE FROM " + TABLE_NAME + " WHERE place_id = ?";
        JDBCUtils.execute(sql, id);
    }
}
